import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import _ from 'lodash'

import { Table, Icon, Tag, Form, Select, Button, message, Modal, Input, Popover} from 'antd';
const Option = Select.Option,
    FormItem = Form.Item;
import {  _validate, fetchSpecialists, updateSpecialist, fetchData, API_URL, PORTRAIT, randomCode } from '../../store/actions';
import SearchInput from '../../components/search-input'

class _SpecialistList extends React.Component{
    constructor(props){
        super(props);
        this.state ={
            filters:{},
            modality:[],
            specialists:[]
        };
        this.onSelectChange = this.onSelectChange.bind(this);
        this.switch = this.switch.bind(this);
        this.fetchSpe = this.fetchSpe.bind(this);
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    fetchSpe(){
        const _this = this,
          token = _this.props.user.accessToken,
          opts = {accessToken:token};
        _this.props.dispatch(fetchSpecialists(opts,function(res1){
            if(_this.state.modality.length < 1){
                const args = {
                    URL:'basedata/modality',
                    IsEnabled:true,
                    IsAuth:true,
                    opts:{accessToken:token},
                    Succ: function(res){
                        _this.setState({
                            specialists:res1.content.data,
                            modality:res.content
                        })
                    }
                };
                _this.props.dispatch(fetchData(args))
            }else{
                _this.setState({
                    specialists:res1.content.data
                })
            }
        }))
    }
    componentWillMount(){
        /* 获取医生列表 */
        this.fetchSpe();
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            images: nextProp.items,
            isFetch:nextProp.isFetch,
            imagesLen:nextProp.items && nextProp.items.length
        })
    }
    onSelectChange(selectedRowKeys) {
        //this.setState({ selectedRowKeys });
    }
    switch(e){
        e.preventDefault();
        const _t = e.target.dataset,
          _this = this,
          id = e.target.id,
          target = _.filter(_this.state.specialists,_o => {
              return _o.account_id == id
          })[0];
        function switchStatus(){
            if(_t.type === 'on'){
                const newData = Object.assign({},target,{status:1});
                _this.props.dispatch(updateSpecialist(id, newData, function(){
                    message.success(`专家（${newData.username}）被启用`,2);
                    _this.fetchSpe()
                }))
            }else if(_t.type === 'off'){
                const newData = Object.assign({},target,{status:0});
                _this.props.dispatch(updateSpecialist(id, newData, function(){
                    message.success(`专家（${newData.username}）被停用`,2);
                    _this.fetchSpe()
                }))
            }
        }
        const modalOpts = {
            title: _t.type == 'on'?'启用医生':'停用医生',
            content: _t.type == 'on'?`确认要启用医生 ${_t.name} 吗？`:`确认要停用医生 ${_t.name} 吗？`,
            okText: _t.type == 'on'?'启用':'停用',
            onOk:switchStatus
        };
        Modal.confirm({...modalOpts})
    }
    goEdit(e){
        e.preventDefault();
        const _t = e.target.dataset;
        this.context.router.push({pathname:`/specialist-edit/${_t.id}`})
    }
    goDetail(e){
        e.preventDefault();
        const _t = e.target.dataset;
        this.context.router.push({pathname:`/specialist-detail/${_t.id}`})
    }
    addSpecialist(e){
        e.preventDefault();
        this.context.router.push({pathname:`/specialist-add`});
    }
    render(){
        const _this = this,
          modalities = _this.state.modality;
        const columns = [{
            title: '专家',
            dataIndex: 'name',
            width:100
        }, {
            title: '性别',
            dataIndex: 'gender',
            className: 'ant-column-status',
            width:50,
            render(text){
                return text === 'M' ? '男' : '女'
            }
        },{
            title:'所属医院',
            dataIndex: 'hospital',
            width:100
        },{
            title:'科室',
            className: 'ant-column-status',
            dataIndex: 'department',
            width:100
        },{
            title:'职称',
            className: 'ant-column-status',
            dataIndex: 'title',
            width:100
        }, {
            title: '阅片类型',
            width:100,
            render(t,record){
                const _act = _.filter(modalities,a => {
                        return _.indexOf(record.modalities,a.id) !== -1
                    }),
                    _names =  (
                        _.map(_act,(_a,i) => {
                            if(i !== 0){
                                return `， ${_a.code}`;
                            }else{
                                return `${_a.code}`;
                            }
                        })
                    );
                return _names
            }
        }, {
            title: '擅长',
            dataIndex: 'domain',
            width:200,
            render(text){
                let _temp ='';
                if(text) {
                    if(text.length > 50)
                        _temp = text.substring(0, 50) + '...';
                    else
                        _temp = text;
                }
                return _temp;
            }
        }/*, {
            title: '审核状态',
            dataIndex: 'ispass',
            className: 'ant-column-status',
            render(text){
                switch (text){
                    case 0:
                        return <span style={{color:'red'}}>待审核</span>;
                    case 1:
                        return <span style={{color:'green'}}>通过审核</span>;
                    case 2:
                        return <span>拒绝</span>;
                    default:
                        return <span style={{color:'#ccc'}}>未知状态</span>
                }
            }
        }*/,{
            title: '状态',
            dataIndex: 'status',
            className: 'ant-column-status',
            width:50,
            render(text){
                switch (text){
                    case 0:
                        return <span style={{color:'red'}}>已停用</span>;
                    case 1:
                        return <span style={{color:'green'}}>正常</span>;
                    default:
                        return <span style={{color:'#ccc'}}>未知状态</span>
                }
            }
        }, {
            title: '操作',
            className: 'ant-column-operation',
            width:100,
            render: (text, record) => {
                switch(record.status){
                    case 0:
                        return (
                            <div>
                                <a href="#" data-type='on' data-name={`${record.name}`} onClick={_this.switch} id={`${record.account_id}`}>启用</a>
                                <span className="ant-divider"> </span>
                                <a href="#" data-id={`${record.account_id}`} onClick={this.goEdit.bind(this)}>编辑</a>
                            </div>
                        );
                    case 1:
                        return (
                            <div>
                                <a href="#" data-type='off' data-name={`${record.name}`} onClick={_this.switch} id={`${record.account_id}`}>停用</a>
                                <span className="ant-divider"> </span>
                                <a href="#" data-id={`${record.account_id}`} onClick={this.goEdit.bind(this)}>编辑</a>
                            </div>
                        );
                    default:
                        return '--';
                }
            }
        }];

        const dataLen = this.state.imagesLen;
        const pagination = {
            total: dataLen,
            showSizeChanger: true,
            onShowSizeChange(current, pageSize) {
                /*console.log('Current: ', current, '; PageSize: ', pageSize);*/
            },
            onChange(current) {
                /*console.log('Current: ', current);*/
            }
        };
        //const { loading, selectedRowKeys } = this.state;

        const rowSelection = {
            /*onChange(selectedRowKeys, selectedRows) {
             console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
             },
             onSelect(record, selected, selectedRows) {
             console.log(record, selected, selectedRows);
             },
             onSelectAll(selected, selectedRows, changeRows) {
             console.log(selected, selectedRows, changeRows);
             }*/
        };
        return (
            <div id="images">
                <div style={{overflow: 'hidden', padding: '10px 0'}}>
                    <div style={{float:'left'}}>
                        <Button type="primary" size="large" icon="plus" onClick={this.addSpecialist.bind(this)}>新增专家</Button>
                    </div>
                    <div style={{float:'right'}}>
                        <SearchInput style={{ width: 200 }} placeholder='请输入关键字查询' />
                    </div>
                </div>
                <Table bordered rowSelection={rowSelection} columns={columns} dataSource={this.state.specialists} pagination={pagination} />
            </div>
        )
    }
}
_SpecialistList = Form.create()(_SpecialistList);
let SpecialistList ;
export default SpecialistList = connect((state)=>{
    const {user} = state.rootReducer;
    return {user}
})(_SpecialistList)